package com.itheima.createThread;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 前两种方法不能返回线程结果
 * Callable 和 FutureTask
 * 1.得到任务对象实现callable接口，重写call方法
 * 2。用Future Task得到Callable对象封装成线程任务的对象
 * 3. 将Future Task交给Thread
 * 4. FutureTask的get方法得到结果
 */


public class ThreadDemo3 implements Callable<String> {
    private int n;

    public ThreadDemo3(int n) {
        this.n = n;
    }

    // 实现callable接口，声明泛型
    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= n; i++) {
            sum+=i;
        }
        return "子线程执行结果:"+sum;
    }
}


class Test3 {
    public static void main(String[] args) {
        Callable<String> callable = new ThreadDemo3(10);
        // Thread只能接runnable，而callable只能给FutureTask
        // FutureTask再给Thread, FutureTask专门用来获取线程的返回值
        FutureTask<String> f1 = new FutureTask<>(callable);
        Thread t = new Thread(f1);
        t.start();
        try {
            // 如果f1任务没有执行完毕，会等待，直到线程跑完； f1是个未来任务，会有检测
            String s = f1.get();
            System.out.println("线程1结果"+s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 5; i++) {
            System.out.println("主线程"+i);
        }

    }
}